Face Detection

importing the libraries

In [8]:
import cv2
import numpy as np 
import matplotlib.pyplot as plt 
  1. FaceDetector Class
In [11]:
class FaceDetector():

    def __init__(self,faceCascadePath):
        self.faceCascade=cv2.CascadeClassifier(faceCascadePath)


    def detect(self, image, scaleFactor=1.1,
               minNeighbors=5,
               minSize=(30,30)):
        
        #function return rectangle coordinates of faces for given image
        rects=self.faceCascade.detectMultiScale(image,
                                                scaleFactor=scaleFactor,
                                                minNeighbors=minNeighbors,
                                                minSize=minSize)
        return rects
  1. load the image
In [12]:
path = "haarcascade_frontalface_default.xml"

face_detection = FaceDetector(path)

# Read the input image
img = cv2.imread('people1.jpg')
In [13]:
def show_image(image):
    plt.figure(figsize=(18,15))
    #Before showing image, bgr color order transformed to rgb order
    plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
    plt.xticks([])
    plt.yticks([])
    plt.show()
In [14]:
show_image(img)
In [15]:
def detect_face(image, scaleFactor, minNeighbors, minSize):
    # face will detected in gray image
    image_gray=cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    faces=face_detection.detect(image_gray,
                   scaleFactor=scaleFactor,
                   minNeighbors=minNeighbors,
                   minSize=minSize)

    for x, y, w, h in faces:
        #detected faces shown in color image
        cv2.rectangle(image,(x,y),(x+w, y+h),(127, 255,0),3)

    show_image(image)
  1. Detecting faces in images
In [87]:
detect_face(image=img, 
            scaleFactor=1.9, 
            minNeighbors=1, 
            minSize=(30,30))

Loading another image

In [75]:
img3 = cv2.imread('people2.jpg')
show_image(img3)
In [79]:
detect_face(image=img3, 
            scaleFactor=1.9, 
            minNeighbors=3, 
            minSize=(30,30))
In [85]:
detect_face(image=img3, 
            scaleFactor=1.9, 
            minNeighbors=1, 
            minSize=(10,30))
In [ ]: